package com.bistu.xiong.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

import static com.bistu.xiong.common.Constance.ERROR_CODE;
import static com.bistu.xiong.common.Constance.SUCCESS_CODE;

/**
 * Created by XiongXiaoJun on 2019/4/9.
 */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化json的时候,如果是null的对象,key也会消失
public class ServerResponse<T> implements Serializable{
    private int code;
    private String msg;
    private T data;

    private ServerResponse(int code){
        this.code = code;
    }
    private ServerResponse(int code, T data){
        this.code = code;
        this.data = data;
    }
    private ServerResponse(int code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    private ServerResponse(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

    @JsonIgnore
    //使之不在json序列化结果当中
    public boolean isSuccess(){
        return this.code == SUCCESS_CODE;
    }
    public int getCode(){
        return code;
    }
    public T getData(){
        return data;
    }
    public String getMsg(){
        return msg;
    }
    public static <T> ServerResponse<T> createBySuccess(){
        return new ServerResponse<T>(SUCCESS_CODE);
    }
    public static <T> ServerResponse<T> createBySuccessMsg(String msg){
        return new ServerResponse<T>(SUCCESS_CODE,msg);
    }
    public static <T> ServerResponse<T> createBySuccess(T data){
        return new ServerResponse<T>(SUCCESS_CODE,data);
    }
    public static <T> ServerResponse<T> createBySuccess(String msg, T data){
        return new ServerResponse<T>(SUCCESS_CODE,msg,data);
    }

    public static <T> ServerResponse<T> createByError(){
        return new ServerResponse<T>(ERROR_CODE);
    }

    public static <T> ServerResponse<T> createByErrorMsg(String errorMessage){
        return new ServerResponse<T>(ERROR_CODE,errorMessage);
    }

    public static <T> ServerResponse<T> createByErrorCodeMsg(int errorCode, String errorMessage){
        return new ServerResponse<T>(errorCode,errorMessage);
    }

}
